#include "reg52.h"
#include "intrins.h"
#include "onewire.h"

sbit relay = P0^4;
sbit buzzer = P0^6;
typedef unsigned char BYTE;
typedef unsigned int WORD;

unsigned char temperature;
unsigned char temp_table[2];
#define FOSC 11059200L

#define T1MS (65536-FOSC/12/1000)   //1ms timer calculation method in 12T mode

sbit TEST_LED = P1^0;               //work LED, flash once per second
WORD count;    

unsigned char code T_display[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
unsigned char code T_COM[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; 

void tm0_isr() interrupt 1 using 1
{
    TL0 = T1MS;                     //reload timer0 low byte
    TH0 = T1MS >> 8;                //reload timer0 high byte
    if (count-- == 0)               //1ms * 1000 -> 1s
    {
					static char i;
     				count = 1;               //reset counter
       				P2=0xe0;P0=~T_display[temp_table[i]];P2=0;
					P2=0xc0;P0=T_COM[i];P2=0;
					i++;
					if(i==2) i=0;
    }
}

void Delay2ms()		//@11.0592MHz
{
	unsigned char i, j;

	_nop_();
	i = 4;
	j = 146;
	do
	{
		while (--j);
	} while (--i);
}

void main()
{
    TMOD = 0x01;                    //set timer0 as mode1 (16-bit)
    TL0 = T1MS;                     //initial timer0 low byte
    TH0 = T1MS >> 8;                //initial timer0 high byte
    TR0 = 1;                        //timer0 start running
    ET0 = 1;                        //enable timer0 interrupt
    EA = 1;                         //open global interrupt switch
    count = 0;                      //initial counter

    while (1);     
	{
		EA=0;
		temperature= (unsigned char)rd_temperature_f();
		EA=1;
		if(temperature>25)
		{
			P2=0x80;P0=~0x01;P2=0x00;
			P2=0xa0;buzzer=0;relay=1;P2=0x00;
		}
		if(temperature<21)
		{
			P2=0x80;P0=~0x02;P2=0x00;
			P2=0xa0;buzzer=1;relay=0;P2=0x00;
		}
		temp_table[0]=temperature/10;
		temp_table[1]=temperature%10;
		Delay2ms();
	}
}

